package com.luochen.cdpt.controller;

import com.luochen.cdpt.eneity.Image;
import com.luochen.cdpt.repository.IFileRepository;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.rest.webmvc.ResourceNotFoundException;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static java.lang.System.getProperty;

/**
 * 图片上传、下载
 *
 * @author star
 * @date 2018/11/27
 */
@Controller
public class ImageController extends ResourceHttpRequestHandler {

    @Autowired
    IFileRepository fileRepository;

    /**
     * 图片上传
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/uploadimg", consumes = "multipart/form-data",method = RequestMethod.POST)
    public @ResponseBody
    ResponseEntity uploadImg(@RequestParam("file") MultipartFile file,
                             HttpServletRequest request) throws IOException {
        return ResponseEntity.ok(resolveFileUpload(file, request));
    }


    protected Map<String, Object> resolveFileUpload(MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String osname = System.getProperty("os.name");
        String path = "D://cdpt_image/" + date + "/";
        if (!osname.toLowerCase().startsWith("win")) {
            path  =  "/www/cdpt_image/" + date + "/";
        }
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdirs();
        }
        Image image = new Image();
        image.setName(multipartFile.getOriginalFilename());
        image.setMediaType(multipartFile.getContentType());
        image.setUploadDate(new Date());
        fileRepository.save(image);
        String fileId = image.getId();
        String filename = multipartFile.getOriginalFilename();
        String filehz = filename.substring(filename.lastIndexOf("."),filename.length());
        File imageFile = new File(dir, fileId+filehz);
        multipartFile.transferTo(imageFile);
        image.setUrl(imageFile.getPath());
        fileRepository.save(image);
        Map<String, Object> file = new HashMap<>();
        file.put("id", fileId);
        return file;
    }

    /**
     * 查看图片
     * @param imageid
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/images/{imageid}", method = {RequestMethod.GET, RequestMethod.HEAD})
    public void getPhoto(@PathVariable("imageid") String imageid,
                         HttpServletRequest request,
                         HttpServletResponse response) throws Exception {
        Image image = fileRepository.findById(imageid).get();
        resolveFileDownload(image, request, response);
    }


    protected void resolveFileDownload(Image image, HttpServletRequest request, HttpServletResponse response) throws Exception {
        if (image == null) {
            throw new ResourceNotFoundException();
        }
        response.setContentType(image.getMediaType());
        if (HttpMethod.GET.matches(request.getMethod())) {
                File file = new File(image.getUrl());
                byte[] bytes = FileUtils.readFileToByteArray(file);
                response.getOutputStream().write(bytes);
            }
        }
}
